<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传图片"
    width="500px"
    destroy-on-close
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="名称" prop="coaNum">
        <el-input 
          v-model="formData.coaNum" 
          placeholder="请输入图片名称"
        />
      </el-form-item>
      
      <!-- <el-form-item label="上传时间" prop="coaDate">
        <el-date-picker
          v-model="formData.coaDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择检测日期"
          style="width: 100%"
        />
      </el-form-item> -->
      
      <el-form-item label="文件类型" prop="type">
        <el-select 
          v-model="formData.type" 
          placeholder="请选择文件类型"
          style="width: 100%"
        >
          <el-option label="JPEG" value="JPEG" />
          <el-option label="PNG" value="PNG" />
          <el-option label="GIF" value="GIF" />
          <el-option label="BMP" value="BMP" />
          <el-option label="TIFF" value="TIFF" />
          <el-option label="SVG" value="SVG" />
        </el-select>
      </el-form-item>

      <el-form-item label="上传人">
  <el-input v-model="formData.uploadBy" disabled />
</el-form-item>
<el-form-item label="上传时间">
  <el-input v-model="formData.createTime" disabled />
</el-form-item>
      
      <el-form-item label="选择文件" prop="file">
        <el-button 
          type="primary" 
          @click="triggerFileSelect"
          style="width: 100%"
        >
          点击选择文件
        </el-button>
        <input
          ref="fileInputRef"
          type="file"
          style="display: none"
          @change="handleFileSelect"
        />
        <div v-if="selectedFileName" class="mt-2 text-sm text-gray-500">
          已选择文件: {{ selectedFileName }}
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ProdPictureApi } from '@/api/product/prodpicture'
// import { create } from 'domain'
// import { console } from 'inspector'
// 如果出现页面无法展示,一直在转圈,很有可能是这里的路由没有配置好
import type { ProdPictureVO } from '@/api/product/prodpicture/index.ts'

const prodId = ref<number | null>(null)
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const fileInputRef = ref<HTMLInputElement>()

const formData = reactive({
  coaNum: '',
  coaDate: '',
  type: '',
  file: null as File | null,
  uploadBy: '',
  createTime: ''
})

const selectedFileName = computed(() => {
  return formData.file ? formData.file.name : ''
})

const formRules = reactive<FormRules>({
  coaNum: [{ required: true, message: '请输入图片名称', trigger: 'blur' }],
  coaDate: [{ required: true, message: '请选择检测日期', trigger: 'change' }],
  type: [{ required: true, message: '请选择文件类型', trigger: 'change' }]
})

const emit = defineEmits<{
  success: []
}>()

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const open = (payload?: { uploadBy?: string; createTime?: string; prodId?: string }) => {
  console.log('open 收到的 payload:', payload)
  formData.createTime = formatDate(payload.createTime) 
  if (payload) {
    formData.uploadBy = payload.uploadBy || ''
    formData.createTime = formatDate(payload.createTime || '')  // 修正空字符串情况
    if (payload?.prodId !== undefined && payload?.prodId !== null) {
  prodId.value = Number(payload.prodId)
}
  }
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  formRef.value?.resetFields()
  formData.file = null
}

const triggerFileSelect = () => {
  fileInputRef.value?.click()
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    formData.file = target.files[0]
  }
}



const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构造 payload 数据
        const payload: ProdPictureVO = {
          name: formData.coaNum,
          type: formData.type,
          updateMan: formData.uploadBy,
          remark: '',
          prodId: prodId.value!, // 现在一定有值
          fileId: 0,
          createTime: new Date(formData.createTime).toISOString()
        }


        console.log('上传的数据：', payload)
        // 选项2: 使用自定义更新接口
         await ProdPictureApi.updatePricter(payload)
        
        ElMessage.success('上传成功')
        handleClose()
        emit('success')
      } catch (err) {
        console.error('上传失败:', err)
        ElMessage.error('上传失败')
      }
    }
  })
}

defineExpose({
  open
})
</script>